import java.awt.Color;

import org.openkinect.processing.Kinect;

import processing.core.PApplet;
import processing.core.PImage;

public class Main extends PApplet {

	Kinect kinect;
	boolean depth = true;
	boolean rgb = true;
	boolean ir = false;

	float deg = 15; // Start at 15 degrees

	private final Object synchronizeObject = new Object();

	public void setup() {
		size(1280, 520);
		// Kinect deadKinect=new Kinect(new PApplet());
		// deadKinect.start();
		// deadKinect.quit();
		kinect = new Kinect(this);
		kinect.start();
		kinect.enableDepth(depth);

		if(rgb)
			kinect.enableRGB(rgb);
		if(ir)
			kinect.enableIR(ir);
		// kinect.tilt(deg);

		Thread checker = new Thread() {
			@Override
			public void run() {
				while (kinect.isAlive()) {
					final int gestureThreshold = 50;
					synchronized (synchronizeObject) {

						if (lastX != 0 && lastY != 0)

							if (Math.abs(lastX - minX) > Math.abs(lastY - minY)) {
								// X distance is greater
								if (lastX - minX > gestureThreshold)
									gesture = "Right";
								else if (lastX - minX < -gestureThreshold)
									gesture = "Left";
							} else {
								// Y distance is greater
								if (lastY - minY > gestureThreshold)
									gesture = "Up";
								else if (lastY - minY < -gestureThreshold)
									gesture = "Down";
							}

						lastX = minX;
						lastY = minY;
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {

					}
				}
			}
		};

		checker.start();
	}

	int lastX = 0;
	int lastY = 0;
	int minX;
	int minY;

	String gesture = "";

	public void draw() {
		background(0);

		int[] pixels = kinect.getRawDepth();

		PImage ir = kinect.getVideoImage();
		PImage image = new PImage(640, 480);

		noStroke();
		synchronized (synchronizeObject) {

			minX = 0;
			minY = 0;

			int minDepth = 2000;

			for (int x = 0; x < 640; x++)
				for (int y = 0; y < 480; y++) {
					float t = ((float) pixels[x + y * 640] - 100) / 512f;

					int depth = pixels[x + y * 640];

					if (depth < minDepth) {
						minDepth = depth;
						minX = x;
						minY = y;
					}

					int myColor = 0;
					if (t < 30)
						myColor = Color.HSBtoRGB(t, 1.0f, 1.0f);

					image.set(x, y, myColor);

				}


			for (int i = -5; i <= 5; i++)
				for (int j = -5; j <= 5; j++)
					ir.set(minX + i, minY + j, Color.RED.getRGB());
		}

		image(image, 0, 0);
		this.text(gesture, 100, 100);
		image(ir, 640, 0);
		// image(kinect.getVideoImage(), 0, 0);
		// image(kinect.getDepthImage(), 640, 0);
		fill(255);
	}

	public void keyPressed() {
		if (key == 'd') {
			depth = !depth;
			kinect.enableDepth(depth);
		}
	}

	public void stop() {
		kinect.quit();
		super.stop();
	}

}
